
    GetMaxK = function(ratio, K){
        
        ### Use dynamic programming to get the maximum ratio against the 
        ### "baseline"
        
        start = c(1, ratio["l0",1], ratio["ak",] * c(1, ratio["l0",1]))
        start[5:8] = start * ratio["lk",]
        starts = apply(matrix(start, 2, ), 2, max)
        names(starts) = c("00","10","01","11")
        
        max.ratio = matrix(NA,K,4)
        colnames(max.ratio) = c("00","10","01","11")
        
        # Choose among l_{k-1},a_{k-1} = "11", "10", "01", "00
        max.ratio[K,"00"] = max(ratio["lK","0"] * c(ratio["aK","1"],1),
                                ratio["aK","0"],1)
        max.ratio[K,"10"] = max(ratio["lK","0"] * c(ratio["aK","1"],1),
                                ratio["aK","0"],1)
        max.ratio[K,"01"] = max(ratio["lK","1"] * c(ratio["aK","1"],1),
                                ratio["aK","0"],1)
        max.ratio[K,"11"] = max(ratio["lK","1"] * c(ratio["aK","1"],1),
                                ratio["aK","0"],1)
        
        for(k in (K-1):2){
        max.ratio[k,"00"] =
                max(ratio["lk","0"] * c(ratio["ak","1"] * max.ratio[k+1,"11"],
                                         max.ratio[k+1,"10"]),
                    ratio["ak","0"] * max.ratio[k+1,"01"],max.ratio[k+1,"00"])
            max.ratio[k,"01"] =
                max(ratio["lk","1"] * c(ratio["ak","1"] * max.ratio[k+1,"11"],
                                         max.ratio[k+1,"10"]),
                    ratio["ak","0"] * max.ratio[k+1,"01"],max.ratio[k+1,"00"])
            max.ratio[k,"10"] =
                max(ratio["lk","0"] * c(ratio["ak","1"] * max.ratio[k+1,"11"],
                                         max.ratio[k+1,"10"]),
                    ratio["ak","0"] * max.ratio[k+1,"01"],max.ratio[k+1,"00"])
            max.ratio[k,"11"] =
                max(ratio["lk","1"] * c(ratio["ak","1"] * max.ratio[k+1,"11"],
                                         max.ratio[k+1,"10"]),
                    ratio["ak","0"] * max.ratio[k+1,"01"],max.ratio[k+1,"00"])
        }
        
        ratio.max = max(max.ratio[2,] * starts)
        
        return(ratio.max)
        
    }